<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 16:04:51
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-22 11:46:16
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建模型" : "编辑模型" }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="120px">
      <el-form-item
        label="模型编码"
        prop="code"
        :rules="[
          { required: true, message: '模型编码不能为空', trigger: 'change' },
          {
            pattern: COMMON_CODE_REG_64,
            message: '请输入有效的模型编码',
            trigger: 'change',
          },
        ]"
      >
        <template slot="label"
          >模型编码
          <el-tooltip
            popper-class="custom-popper"
            :content="COMMON_CODE_REG_64_MSG"
            placement="top"
          >
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-input
          :disabled="!isNew"
          v-model="formData.code"
          style="width: 400px"
          placeholder="请输入模型编码"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item
        label="模型名称"
        prop="name"
        :rules="[
          { required: true, message: '模型名称不能为空', trigger: 'change' },
          {
            validator: validatorModulename,
            trigger: 'change',
          },
        ]"
      >
        <el-input
          v-model="formData.name"
          style="width: 400px"
          placeholder="请输入模型名称"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item
        label="模型类型"
        prop="type"
        :rules="[
          { required: true, message: '请选择模型类型', trigger: 'change' },
        ]"
      >
        <el-radio-group v-model="formData.type" :disabled="!isNew">
          <el-radio
            v-for="(value, key) in MODULE_TYPE_ENUM"
            :key="key"
            :label="key"
            >{{ value }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <template v-if="formData.type === 'ENTITY'">
        <el-form-item label="模型标识" prop="supportProcess">
          <el-checkbox
            :disabled="!isNew"
            v-model="formData.supportProcess"
            @change="handleChangeSupportProcess"
          >
            流程业务模型
          </el-checkbox>
          <el-form-item
            style="display: inline-block; margin: 0px 30px"
            prop="supportStatus"
          >
            <el-checkbox
              :disabled="!isNew"
              v-model="formData.supportStateModel"
              @change="handleChangeSupportStatus"
            >
              状态机
            </el-checkbox>
          </el-form-item>
          <el-form-item
            style="display: inline-block; margin: 0px 30px"
            prop="supportTree"
          >
            <el-checkbox
              :disabled="!isNew"
              v-model="formData.supportTree"
              @change="handleChangeSupportTree"
            >
              树形结构
            </el-checkbox>
          </el-form-item>
        </el-form-item>
        <el-form-item
          v-if="formData.supportStateModel"
          label="关联状态机"
          prop="stateModelKey"
          :rules="[
            {
              required: true,
              message: '请选择状态机',
              trigger: 'change',
            },
          ]"
        >
          <tree-select
            :disabled="!isNew"
            style="width: 400px"
            v-model="formData.stateModelKey"
            filterable
            :fieldMap="{
              value: 'key',
              label: 'name',
              disabled: 'disabled',
            }"
            :filterNodeMethod="filterNodeMethod"
            :treeData="stateModelTree"
          />
        </el-form-item>
      </template>

      <template v-else-if="formData.type === 'VIEW'">
        <el-form-item
          label="数据源"
          prop="datasourceId"
          :rules="[
            { required: true, message: '请选择数据源', trigger: 'change' },
          ]"
        >
          <el-select
            filterable
            style="width: 400px"
            v-model="formData.datasourceId"
            placeholder="请选择数据源"
          >
            <el-option
              v-for="ds in dsList"
              :key="ds.id"
              :value="ds.id"
              :label="ds.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="视图名"
          prop="viewName"
          :rules="[
            { required: true, message: '视图名不能为空', trigger: 'change' },
          ]"
        >
          <el-input
            v-model="formData.viewName"
            style="width: 400px"
            placeholder="请输入视图名"
            :maxlength="64"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <template v-else-if="formData.type === 'VIRTUAL'">
        <el-form-item label="模型标识" prop="supportProcess">
          <el-checkbox
            :disabled="!isNew"
            v-model="formData.supportProcess"
            @change="handleChangeSupportProcess"
          >
            流程业务模型
          </el-checkbox>
          <el-form-item
            style="display: inline-block; margin: 0px 30px"
            prop="supportStateModel"
          >
            <el-checkbox
              :disabled="!isNew"
              v-model="formData.supportStateModel"
              @change="handleChangeSupportStatus"
            >
              状态机
            </el-checkbox>
          </el-form-item>
          <el-form-item
            style="display: inline-block; margin: 0px 30px"
            prop="supportTree"
          >
            <el-checkbox
              :disabled="!isNew"
              v-model="formData.supportTree"
              @change="handleChangeSupportTree"
            >
              树形结构
            </el-checkbox>
          </el-form-item>
        </el-form-item>
        <el-form-item
          v-if="formData.supportStateModel"
          label="关联状态机"
          prop="stateModelKey"
          :rules="[
            {
              required: true,
              message: '请选择状态机',
              trigger: 'change',
            },
          ]"
        >
          <tree-select
            style="width: 400px"
            :disabled="!isNew"
            v-model="formData.stateModelKey"
            :fieldMap="{
              value: 'key',
              label: 'name',
              disabled: 'disabled',
            }"
            :treeData="stateModelTree"
          />
        </el-form-item>
        <el-form-item
          label="第三方服务"
          prop="httpServiceId"
          :rules="[
            // { required: true, message: '请选择第三方服务', trigger: 'change' },
          ]"
        >
          <el-select
            filterable
            clearable
            style="width: 400px"
            v-model="formData.httpServiceId"
            placeholder="请选择第三方服务"
          >
            <el-option
              v-for="item in httpServiceList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item label="模型描述">
        <el-input
          type="textarea"
          v-model="formData.description"
          style="width: 400px"
          placeholder="请输入模型描述"
          :maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="submit"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import lodash from "lodash";
import { MODULE_TYPE_ENUM } from "@/utils/enum";
import { COMMON_CODE_REG_64, COMMON_CODE_REG_64_MSG } from "@/utils/reg";

import { postHmmodel, putHmmodel } from "@/apis/paas/HmModelController.js";
import { getHmdatasourcePageList } from "@/apis/paas/HmDatasourceController.js";
import { getHmhttpservicePageList } from "@/apis/paas/HmHttpServiceController.js";
import { getHmstatemodelfolderListTree } from "@/apis/paas/HmStateModelFolderController.js";
const defaultaFormData = {
  type: Object.keys(MODULE_TYPE_ENUM)[0],
};
function disabledTreeNodeCreate(tree) {
  return lodash.cloneDeep(tree).map((node) => {
    node.disabled = node.type === "folder";
    if (node.stateModelList) {
      node.id = "folder" + node.id;
      node.children = node.stateModelList || [];
      node.children.forEach((item) => {
        item.name = `${item.name}（${item.key}）`;
      });
    }
    return node;
  });
}
export default {
  data() {
    return {
      showVisible: false,
      loading: false,
      formData: {},
      MODULE_TYPE_ENUM,
      COMMON_CODE_REG_64,
      COMMON_CODE_REG_64_MSG,
      dsList: [],
      httpServiceList: [],
      stateModelTree: [],
      callback: () => {},
      validatorModulename: (rule, value, callback) => {
        if (value.search(/'|"/) > -1) {
          callback(new Error("模型名称不能带引号"));
        } else {
          callback();
        }
      },
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
  },

  watch: {
    "formData.type": {
      handler: function (value) {
        if (value === "VIEW" && this.dsList.length === 0) {
          this.loadDsList();
          return;
        }
        if (value === "VIRTUAL" && this.httpServiceList.length === 0) {
          this.loadHttpServiceList();
          return false;
        }
      },
      immediate: true,
    },
    "formData.supportStateModel": {
      handler: function (value) {
        if (value) {
          this.loadStateModelList();
        }
      },
      immediate: true,
    },
    showVisible(value) {
      if (!value) {
        this.dsList = [];
        this.httpServiceList = [];
      }
    },
  },

  methods: {
    addForm(record = {}) {
      this.formData = {
        ...record,
        type: defaultaFormData.type,
        supportTree: false,
        supportProcess: false,
        supportStateModel: false,
      };
      return this.showModel();
    },
    editForm(record) {
      this.formData = { ...record };
      if (this.formData.type === "VIRTUAL") {
        this.loadHttpServiceList();
      }
      if (this.formData.type === "VIEW") {
        this.loadDsList();
      }
      return this.showModel();
    },
    showModel() {
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },

    loadDsList() {
      getHmdatasourcePageList({
        pageSize: 100000,
        pageNo: 1,
      }).then((res) => {
        this.dsList = res.data;
      });
    },
    loadHttpServiceList() {
      getHmhttpservicePageList({
        pageSize: 100000,
        pageNo: 1,
      }).then((res) => {
        this.httpServiceList = res.data;
      });
    },
    loadStateModelList() {
      getHmstatemodelfolderListTree().then((res) => {
        res.forEach((node) => {
          node.type = "folder";
        });
        this.stateModelTree = disabledTreeNodeCreate(res || []);
      });
    },
    async submit() {
      try {
        await this.$refs.form.validate();
        const {
          id,
          code,
          name,
          type,
          supportProcess,
          supportTree,
          supportStateModel,
          stateModelKey,
          description,
          datasourceId,
          viewName,
          httpServiceId,
          folderId,
        } = this.formData;
        let params = {};
        let request = null;
        if (this.isNew) {
          params = { code, name, type, description, folderId };
          request = postHmmodel;
        } else {
          params = { id, name, description };
          request = putHmmodel;
        }
        if (type === "ENTITY") {
          params = {
            ...params,
            supportProcess,
            supportTree,
            supportStateModel,
            stateModelKey,
          };
        } else if (type === "VIEW") {
          params = {
            ...params,
            datasourceId,
            viewName,
          };
        } else if (type === "VIRTUAL") {
          params = {
            ...params,
            supportProcess,
            supportTree,
            httpServiceId,
            supportStateModel,
            stateModelKey,
          };
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        this.loading = true;
        request(params)
          .then((res) => {
            this.showVisible = false;
            this.callback({
              id: res,
              type,
            });
          })
          .finally(() => {
            this.loading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.name && data.name.indexOf(value) !== -1;
    },
    // 支持树形与支持流程模型，状态机互斥
    handleChangeSupportProcess(value) {
      if (value) {
        this.formData.supportTree = false;
        this.formData.supportStateModel = false;
      }
    },
    handleChangeSupportStatus(value) {
      if (value) {
        this.formData.supportTree = false;
        this.formData.supportProcess = false;
      }
    },
    handleChangeSupportTree(value) {
      if (value) {
        this.formData.supportStateModel = false;
        this.formData.supportProcess = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
